#!/usr/bin/env python
"""
The MIT License (MIT)
Copyright © 2022 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-esp32-walkie-talkie
"""
import socket
import pyaudio

HOST = ('0.0.0.0', 7890)
CHUNK = 1024 * 5

def main():
	udp_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	udp_server.bind(HOST)
	print(f'udp server start on port {HOST[1]}')

	audio = pyaudio.PyAudio()
	stream = audio.open(
		format=pyaudio.paInt16,
		channels=1,
		rate=16000,
		output=True,
		# frames_per_buffer=CHUNK
	)
	print('audio output device initialized')

	wave_sample_mv = memoryview(bytearray(CHUNK))

	print('waiting for wave samples...')
	while True:
		length = udp_server.recv_into(wave_sample_mv, CHUNK)
		stream.write(bytes(wave_sample_mv[0:length]))


if __name__ == '__main__':
	try:
		main()
	except KeyboardInterrupt:
		exit(0)
